"""
商品数据DTO

@author liaochangyi
@since 2025-01-25
"""

from typing import Dict, Any, List, Union
from .goods_detail_dto import GoodsDetailDto


class GoodsDataDto:
    """商品数据DTO"""
    
    def __init__(self, goods_data_dict=None):
        """
        初始化商品数据
        
        Args:
            goods_data_dict: 商品数据字典
        """
        self.cost_price = None  # 订单原价
        self.receipt_id = None  # 商品小票ID
        self.goods_detail = None  # 单品列表
        
        if goods_data_dict:
            self.cost_price = goods_data_dict.get('cost_price')
            self.receipt_id = goods_data_dict.get('receipt_id')
            goods_detail_data = goods_data_dict.get('goods_detail', [])
            if goods_detail_data:
                self.goods_detail = [GoodsDetailDto(detail) for detail in goods_detail_data]
    
    def set_goods_detail(self, goods_detail: List[Union[Dict[str, Any], GoodsDetailDto]]):
        """
        设置商品详情列表
        
        Args:
            goods_detail: 商品详情列表，可以是字典列表或GoodsDetailDto对象列表
        """
        if goods_detail:
            self.goods_detail = []
            for detail in goods_detail:
                if isinstance(detail, dict):
                    self.goods_detail.append(GoodsDetailDto(detail))
                elif isinstance(detail, GoodsDetailDto):
                    self.goods_detail.append(detail)
                else:
                    # 如果不是字典也不是GoodsDetailDto对象，尝试转换为GoodsDetailDto
                    self.goods_detail.append(GoodsDetailDto(detail))
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'cost_price': self.cost_price,
            'receipt_id': self.receipt_id,
            'goods_detail': [detail.to_dict() for detail in self.goods_detail] if self.goods_detail else []
        } 